<?php

include_once('nano.php');

function NanoLexer($str)
{
	$str = strtolower($str);
	$str = str_replace(array("\r\n", "\n\r", "\r", "\n"), "\n", $str);
	$lines = explode("\n", $str);
	$tokens = array();
	foreach($lines as $l)
	{
		$t = NanoLexLine($l);
		if($t == null) continue;
		$tokens[] = $t;
	}
	return $tokens;
}

function NanoLexLine($l)
{
	$tokens = array();
	$splits = preg_split('/[ \t]+|([:,\(\)\+;~-])/', $l, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
	if(empty($splits)) return null;
	foreach($splits as $s)
	{
		if(is_special($s))
		{
			$tokens[] = array('type' => 'special', 'val' => $s);
			if($s == ';') break;
		}
		else if(is_numeric($s) && (int)$s == $s)
			$tokens[] = array('type' => 'int', 'val' => (int)$s);
		else if(is_instruction($s))
			$tokens[] = array('type' => 'inst', 'val' => $s);
		else if(is_register($s))
			$tokens[] = array('type' => 'reg', 'val' => $s);
		else if(is_flag($s))
			$tokens[] = array('type' => 'flag', 'val' => $s);
		else if(is_label($s))
			$tokens[] = array('type' => 'label', 'val' => $s);
		else
			$tokens[] = array('type' => 'unknown', 'val' => $s);
	}
	return $tokens;
}

function is_instruction($str)
{
	global $instructions;
	return array_key_exists($str, $instructions);
}

function is_register($str)
{
	global $registers;
	return array_key_exists($str, $registers);
}

function is_flag($str)
{
	global $flags;
	return array_key_exists($str, $flags);
}

function is_special($str)
{
	$special = array(':', ',', '(', ')', '+', '-', '~', ';');
	return in_array($str, $special);
}

function is_label($str)
{
	if($str[0] < 'a' || $str[0] > 'z') return false;
	for($i = 1; $i<count($str); $i++)
		if(($str[$i] < 'a' || $str[$i] > 'z') && ($str[$i] < '0' || $str[$i] > '9'))
			return false;
	return true;
}

?>